package Util;

import java.util.StringTokenizer; 

public class Validador extends Object {
	
	// calcula digito verificador do CPF a partir dos 9 numeros passados
	private static String calcDigVerif(String num) {
		Integer primDig, segDig;
		int soma = 0, peso = 10;
		for (int i = 0; i < num.length(); i++)
			soma += Integer.parseInt(num.substring(i, i + 1)) * peso--;

		if (soma % 11 == 0 | soma % 11 == 1)
			primDig = new Integer(0);
		else
			primDig = new Integer(11 - (soma % 11));

		soma = 0;
		peso = 11;
		for (int i = 0; i < num.length(); i++)
			soma += Integer.parseInt(num.substring(i, i + 1)) * peso--;

		soma += primDig.intValue() * 2;
		if (soma % 11 == 0 | soma % 11 == 1)
			segDig = new Integer(0);
		else
			segDig = new Integer(11 - (soma % 11));

		return primDig.toString() + segDig.toString();
	}

	public static String geraCPF() {
		String iniciais = "";
		Integer numero;
		for (int i = 0; i < 9; i++) {
			numero = new Integer((int) (Math.random() * 10));
			iniciais += numero.toString();
		}
		return iniciais + calcDigVerif(iniciais);
	}

	// valida CPF com ou sem máscara
	public static boolean validaCPF(String cpf) {
		cpf = cpf.trim();

		char [] chars;
		int i;
		
		try { // Verifica se contem apenas numeros
				int [] testNum = new int[cpf.length()];
			for (i = 0; i < testNum.length; i++) {  
	            testNum[i] = Integer.parseInt(cpf.substring(i, i + 1));  
	        }  
			chars = cpf.toCharArray();
		} catch(NumberFormatException e) {
			return false;	
		}

		
		for (i = 0; i < chars.length; i++) {
			if (chars[i] == ' ') {
				return false;
			}
		}
		cpf = unmask(cpf.trim());
		if (cpf.length() < 11 || cpf.length() > 11) {
			return false;
		}
		String numDig = cpf.substring(0, 9);
		return calcDigVerif(numDig).equals(cpf.substring(9, 11));
	}

	// tira a mascara da String ("/", ".", "-")
	public static String unmask(String masked) {
		StringTokenizer tokens = new StringTokenizer(masked, ".");
		String unmasked = "";
		while (tokens.hasMoreTokens()) {
			unmasked = unmasked + tokens.nextToken();
		}
		masked = unmasked;
		unmasked = "";
		tokens = new StringTokenizer(masked, "/");
		while (tokens.hasMoreTokens()) {
			unmasked = unmasked + tokens.nextToken();
		}
		masked = unmasked;
		unmasked = "";
		tokens = new StringTokenizer(masked, "-");
		while (tokens.hasMoreTokens()) {
			unmasked = unmasked + tokens.nextToken();
		}
		return unmasked;
	}

}
